﻿/*
 * DotNetCrypt - an open source library of cryptographic algorithms for .NET
 * Copyright (C) 2009 David Musgrove
 * 
 * This file is part of DotNetCrypt.
 *
 * DotNetCrypt is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DotNetCrypt is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using NUnit.Framework;

namespace DotNetCrypt.Tests
{
    static internal class TestUtils
    {
        static public byte[] StringToHex(string key)
        {
            var result = new byte[key.Length / 2];
            for (int index = 0; index < key.Length; index += 2)
            {
                result[index / 2] = Byte.Parse(key.Substring(index, 2), NumberStyles.AllowHexSpecifier);
            }
            return result;
        }

        static public void AssertByteArray(string expectedString, IEnumerable<byte> cipher)
        {
            byte[] expected = StringToHex(expectedString);
            CollectionAssert.AreEquivalent(expected, cipher);
        }

        static public byte[] Transform(ICryptoTransform transform, byte[] plain)
        {
            var stream = new MemoryStream();
            var cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(plain, 0, plain.Length);
            cryptoStream.FlushFinalBlock();
            var length = (int)stream.Length;
            stream.Position = 0;
            var result = new byte[length];
            stream.Read(result, 0, length);
            return result;
        }

        static public byte[] TransformWithCryptoStream(byte[] plainBuffer, ICryptoTransform transform)
        {
            var stream = new MemoryStream();
            var cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(plainBuffer, 0, plainBuffer.Length);
            cryptoStream.FlushFinalBlock();
            var length = (int)stream.Length;
            stream.Position = 0;
            var result = new byte[length];
            stream.Read(result, 0, length);
            return result;
        }
    }
}